const express = require("express");
const fs = require("fs");
const moment = require("moment")

const db = require("./../lib/DBhelper");
let apiRouter = express.Router({});

//登录
apiRouter.post("/login", function(request, response, next) {
    let params = [
        request.body.utel,
        request.body.upwd
    ]
    let sql = "SELECT `uid`,`utel`,`utype`,`ustatus` FROM `userinfo` WHERE `ustatus`=1 AND `utel`=? AND `upwd`=?";
    db.exec(sql, params, (err, result) => {
        if (!err && result.length >= 1) {
            //把当前登陆者的信息保存到session
            request.session["userInfo"] = Object.assign({}, result);
            response.json({
                msg: "登录成功",
                data: result,
                status: 1
            })
        } else {
            response.json({
                msg: "登录失败",
                status: -1
            })
        }
    })
})

//注册
apiRouter.post("/reg", function(request, response, next) {
    let params = [
        request.body.utel,
        request.body.upwd
    ]
    let sql = "INSERT INTO `userinfo` (`utel`,`upwd`) VALUE(?,?);"
    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msgP: "注册失败",
                status: -2,
                err
            })
            return;
        }
        if (result.affectedRows >= 1) { //受影响行数大于一表示插入成功
            response.json({
                msg: "注册成功",
                status: 1
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -1
            })
        }
    })
})

apiRouter.get("/list", (request, response, next) => {
    var resJson = JSON.parse(fs.readFileSync("./data/list.json").toString());
    response.json(resJson)
})

//根据id返回一条数据
apiRouter.get("/ById/:id", (request, response, next) => {
    let id = request.params.id

    var resArr = JSON.parse(fs.readFileSync("./data/list.json").toString());
    //查询之后得到一个新的数
    var resList = resArr.filter(el => {
        return el.id == id;
    })
    if (resList.length >= 1) {
        response.json({
            msg: "查询成功",
            status: 1,
            data: resList[0]
        })
    } else {
        response.json({
            msg: "查询失败",
            status: -1,
            data: null
        })
    }
})


//加入购物车
apiRouter.post("/addCart", async(request, response, next) => {
    var paramsAdd = [
        request.body.uid, //购买者
        request.body.pid, //产品编号
        request.body.psize, //产品尺码
        request.body.pcolor, //产品颜色
        request.body.pimg, //产品图片
        request.body.pprice, //产品价格
    ]
    var querySql = "SELECT * FROM `goods` WHERE `p_status`=1 AND `p_complete`=1 AND `u_id`=? AND `p_id`=? AND `p_size`=? AND `p_color`=? AND `p_img`=? AND `p_price`=?";

    var res = await db.execAsync(querySql, paramsAdd);


    if (res.length >= 1) {
        //已经购买修改数量
        let paramsUpdate = [
            request.body.pnum, //数量
            request.body.uid, //购买者
            request.body.pid, //产品编号
            request.body.psize //产品尺码
        ]
        var updateSql = "UPDATE `goods` SET `p_num`=`p_num`+?,`p_total`=`p_num`*`p_price` WHERE `p_status`=1 AND `p_complete`=1 AND `u_id`=? AND `p_id`=? AND `p_size`=?";

        var res = await db.execAsync(updateSql, paramsUpdate);
        if (res.affectedRows >= 1) {
            response.json({
                msg: "加入购物车成功u",
                status: 1
            })
        } else {
            response.json({
                msg: "加入购物车失败u",
                status: -11
            })
        }
    } else {
        var paramsInsert = [
            request.body.uid,
            request.body.pid, //产品编号
            request.body.pimg, //图片
            request.body.pname, //名称
            request.body.pcolor, //颜色
            request.body.psize, //尺码
            request.body.pprice, //单价
            request.body.pnum, //数量
            request.body.ptotal, //总金额
            moment().format("YYYY-MM-DD HH:mm:ss") //时间
        ]
        var insertSql = "INSERT INTO `goods` (`u_id`,`p_id`,`p_img`,`p_name`,`p_color`,`p_size`,`p_price`,`p_num`,`p_total`,`p_time`) VALUE (?,?,?,?,?,?,?,?,?,?)"

        var res = await db.execAsync(insertSql, paramsInsert);
        if (res.affectedRows >= 1) {
            response.json({
                msg: "加入购物车成功i",
                status: 1
            })
        } else {
            response.json({
                msg: "加入购物车失败i",
                status: -11
            })
        }
    }
})


apiRouter.get("/carts", async(request, response, next) => {
    let params = [
        request.query.uid
    ]
    let query = "SELECT * FROM `goods` WHERE `p_status`=1 AND `p_complete`=1 AND `u_id`=?"
    var res = await db.execAsync(query, params);
    response.json({
        msg: res.length >= 1 ? "查询成功" : "查询失败",
        status: res.length >= 1 ? 1 : -1,
        data: res
    })
})

//修改数量
apiRouter.post("/modify", async(request, response, next) => {
    let params = [
        request.body.pnum,
        request.body.cid,
    ]
    let sql = "UPDATE `goods` SET `p_num`=?,`p_total`=`p_num`*`p_price` WHERE `c_id`=? AND `p_status`=1 AND `p_complete`=1";
    var res = await db.execAsync(sql, params);
    response.json({
        msg: res.affectedRows >= 1 ? "修改成功" : "修改失败",
        status: res.affectedRows >= 1 ? 1 : -1
    })
})


//删除
apiRouter.post("/delete", async(request, response, next) => {
    let params = [
        request.body.cid
    ]
    let sql = "UPDATE `goods` SET `p_status`=0 WHERE `c_id`=? AND `p_status`=1 AND`p_complete`=1";
    var res = await db.execAsync(sql, params);
    response.json({
        msg: res.affectedRows >= 1 ? "删除成功" : "删除失败",
        status: res.affectedRows >= 1 ? 1 : -1
    })
})


apiRouter.get("/quit", (request, response, next) => {
    request.session["userInfo"] = null;
    response.clearCookie("logoInfo");
    response.json({
        msg: "退出成功",
        status: 1
    })
})

module.exports = apiRouter;